<template>
  <div :class="prefixCls">
    <template v-for="(item, idx) in dataSource" :key="idx">
      <div
        class="model-item"
        :class="{
          'model-item-preview': isOpearte,
          modelActive: isOpearte && activeIdx === idx,
        }"
        :style="getStyle(item)"
        @click.stop="changeType(item, idx)"
      >
        <div
          @click.stop="handleDel(idx)"
          v-if="isOpearte"
          class="close p-1 z-2 absolute -top-1 -right-1"
        >
          <Icon icon="ant-design:close-outlined" />
        </div>
        <!-- 复合组件分发 -->
        <ComModelPage
          :class="[isOpearte && 'pointer-events-none']"
          :total="dataSource.length"
          :pageType="PageTypeEnum.TILED"
          :data="item"
        />
      </div>
    </template>
  </div>
</template>

<script lang="ts" setup name="TiledPage">
  import { computed, onMounted } from 'vue';
  import ComModelPage from '../components/ComModelPage.vue';
  import { Icon } from '/@/components/Icon';
  import { PageTypeEnum } from '../typing';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { getCSSValue } from '/@/utils';
  import { useComplexContext } from '../useComplexContext';

  const { prefixCls } = useDesign('h-tiled');
  onMounted(() => {});
  const props = defineProps({
    preview: Boolean,
    active: Number,
    dataSource: {
      type: Array as PropType<any[]>,
      default: () => [],
    },
  });
  const { isChild } = useComplexContext();
  const isOpearte = computed(() => {
    return props.preview && !isChild;
  });
  const emit = defineEmits(['update:active', 'change', 'del', 'detail']);

  const activeIdx = computed({
    get: () => {
      return props.active || 0;
    },
    set: (v) => {
      emit('update:active', v);
    },
  });
  function handleDel(idx) {
    emit('del', idx);
    activeIdx.value = idx > 1 ? idx - 1 : 0;
  }
  function changeType(data, idx) {
    activeIdx.value = idx;
    emit('change', data);
  }

  const getStyle = (item) => {
    const { width, height } = item;

    return {
      width: getCSSValue(width, '100%'),
      height: getCSSValue(height),
      overflow: 'hidden auto',
    };
  };
</script>

<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-h-tiled';

  .@{prefix-cls} {
    height: 100%;
    display: flex;
    flex-wrap: wrap;

    .model-item {
      position: relative;

      .close {
        display: none;
      }

      &.model-item-preview {
        &:hover,
        &.modelActive {
          cursor: pointer;
          border: 1px solid @primary-color;

          .close {
            display: block;
            color: @primary-color;

            &:hover {
              color: @error-color;
              cursor: pointer;
            }
          }
        }
      }
    }
  }
</style>
